class Monster extends Moveable{
  constructor({name, x, y, width, height, game, hp, speed}) {
    super({name, type: MOB_TYPES.MONSTER, x, y, width, height, game, hp, speed})
    this.tick = 0;
    this.activeEngine = setInterval(() => {
      if(this.game && this.game.player) {
        // 计算玩家当前到自己的角度值以及自己下一步应该移动到的位置
        let {angle, targetX, targetY} = getAngle(this.game.player, this)
        this.angle = angle
        const rst = this.preMove(speed, true)
        targetX = targetX || rst.x
        targetY = targetY || rst.y
        this.move(targetX, targetY);
        if(rst.isOutSide) {
          // 自身完全移动到屏幕外时的事件，如果是横版过关会用到
          // 当怪物移动到画面外之后应该停止动作，然后当所有属于他的子弹都不在画面中的时候销毁
          // 此时应该告知game进行处理
          this.emit('outSide')
        }
        let now = Date.now()
        // 每隔一段时间开始发射子弹
        if(!this.tick || now - this.tick > MONSTER_SHOT_DELAY) {
          this.tick = now;
          // 每次发射MONSTER_PROJECTILE_PER_SHOT颗子弹
          // 每颗子弹间隔MONSTER_PROJECTILE_DELAY_PER_SHOT秒
          for(let i = 0; i < MONSTER_PROJECTILE_PER_SHOT; i ++) {
            setTimeout(() => {
              if(!this.game) return
              let {angle} = getAngle(this.game.player, this)
              let projectile = new Projectile({
                name: 'bullet',
                type: MOB_TYPES.BULLET,
                x: this.x,
                y: this.y,
                width: 20, 
                height: 20,
                game: this.game,
                hp: 20,
                speed: this.speed * 1.5,
                angle
              })
              projectile.on('move', ({x, y}) => {
                // 向game派发子弹移动事件，交由外部统一处理
                // 注意：这里的this是monster，不是子弹
                this.emit('bulletMove', projectile)
              })
              .on('outSide', () => {
                // 当子弹移出画面外时销毁掉
                projectile.release();
                this.removeProjectile(projectile);
              })
              this.projectiles.push(projectile)
            }, MONSTER_PROJECTILE_DELAY_PER_SHOT * i)
          }
        }
      }
    }, 10)
  }
  get hp() {
    return this.hits
  }
  set hp(hp) {
    if(hp < 0) {
      hp = 0;
    }
    this.hits = hp;
    if(!this.hp) {
      this.emit('dead', this.hp)
      this.release();
    }
  }
  stop() {
    // 清除自己的定时器
    clearInterval(this.activeEngine);
    this.activeEngine = null;
    super.release();
    // 清除子弹的定时器
    this.projectiles.forEach(p => p.release());
  }
}
